package com.zzl.study.sharding.algorithm.standard;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.algorithm.sharding.range.AbstractRangeShardingAlgorithm;

import java.util.*;

/**
 * @author: zhangzl
 * @date: 2022/7/17 12:16
 * @version: 1.0
 * @description: 书本表自定义类分片算法：standard策略，对书本表的price进行范围分片
 */
public class BookRangeStandardShardingAlgorithm extends AbstractRangeShardingAlgorithm {

    /**
     * 价格分片区间[0, 100)/[100, 200)/[200, 300)/[300, 400)/[400, 500)/[500, +无穷)
     */
    private static final Long[] PRICE_RANGE_ARRAY = {100L, 200L, 300L, 400L, 500L};

    @Override
    protected Map<Integer, Range<Comparable<?>>> calculatePartitionRange(Properties props) {// props在本例中无用
        List<Long> partitionRanges = Arrays.asList(PRICE_RANGE_ARRAY);// 这个结果必须是Long类型的
        Map<Integer, Range<Comparable<?>>> result = new HashMap<>(partitionRanges.size() + 1, 1);
        for (int i = 0; i < partitionRanges.size(); i++) {
            Long rangeValue = partitionRanges.get(i);
            if (0 == i) {
                result.put(0, Range.lessThan(rangeValue));
            } else {
                Long previousRangeValue = partitionRanges.get(i - 1);
                result.put(i, Range.closedOpen(previousRangeValue, rangeValue));
            }
            if (i == partitionRanges.size() - 1) {
                result.put(i + 1, Range.atLeast(rangeValue));
            }
        }
        return result;
    }

}
